<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;
use app\api\model\ChimiEvent;
use app\api\model\LinUser;
use app\api\model\LiveVoice;
use app\api\model\VideoDoulaoban;
use app\api\model\VideoEvent;
use app\api\model\VideoProduct;
use app\api\model\VideoProductMaterial;
use app\api\model\VideoProductVideos;
use app\api\model\Config;
use app\api\service\token\LoginToken;
use app\api\service\VideoService;
use app\lib\doubao\Doubao;
use app\lib\qiniu\Qiniu;
use think\Request;
use think\Db;
use think\Exception;

require_once '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
require_once '../vendor/PHPExcel/Classes/PHPExcel/Reader/Excel5.php';
use PHPExcel;
use PHPExcel_IOFactory;

class Video
{

    // 添加视频素材 商品
    public function addProductVideos(Request $request)
    {
        $data = $request->post();
        // 判断是否添加
        $count = (new VideoService())->addProductVideos($data);

        return  writeJson(200,$count , '新增商品视频');
    }


    public function addDoulaobanProduct(Request $request)
    {
        $data = $request->post();
        // 判断是否添加
        $count = (new VideoService())->addDoulaobanProduct($data);

        return  writeJson(200,$count , '新增抖老板商品');
    }

    public function getDoulaobanToCollect(Request $request)
    {

        $item = VideoDoulaoban::where('status', 1)
            ->orderRand()->findOrEmpty();
        if (!$item->isEmpty()) {
            $item->status = 2;
            $item->get_time = date('Y-m-d H:i:s');
            $item->save();
            return writeJson(200, $item, '素材获取');
        }

        return writeJson(200, null, '素材获取');
    }

    public function doulaobanRewrite(Request $request)
    {
        $params = $request->post();

        $result = VideoDoulaoban::where('id',$params["id"])->findOrEmpty();

        if (!$result->isEmpty()) {
            $result->save($params);
        }
        return  writeJson(200, $result, '回填抖老板商品');
    }




    /*
     * 这里字幕采集的插件做一个按钮 点击能够自动轮询库里的视频（交给金文）
        抖老板待采集商品xx  （status=1 ）
        待采集视频的商品xxx   (status=1 )

        待标注的视频数量xxx  (check=0)
        待采集文案的视频数xxx (text_status=1)
        待切割的视频数量xx (status=1 and check=1 and text_status=3)
     *
     * */

    public function data()
    {
        //待采集视频的商品xxx   (status=1 or status=2)
        $dcjsp = VideoProduct::where('status', 1)->count();

        // 抖老板待采集商品xx  （status=1 ）
        $dlb_dcjsp = VideoDoulaoban::where('status', 1)->count();

        // 待标注的视频数量xxx  (check=0 & text_status=3)
        $dbzsp = VideoProductVideos::where('check', 0)->where('text_status',3)->count();

        // 待采集文案的视频数xxx (text_status=1)
        $dcjwa = VideoProductVideos::where('text_status', 1)->count();

        // 待切割的视频数量xx (status=1 and check=1 text_status=3(有了颗粒度才能拆))
        $dqgsp = VideoProductVideos::where('check', 1)
            ->where('text_status',3)
            ->where('status',1)
            ->count();

        $data = [
          "抖老板待采集商品数" => $dlb_dcjsp,
            "待采集视频的商品" => $dcjsp,
            "待标注的视频数量" => $dbzsp,
            "待采集文案的视频数" => $dcjwa,
            "待切割的视频数量" => $dqgsp
        ];

        return  writeJson(200, $data, '数据看板');


    }




    public function getVideoToCut(Request $request)
    {

        $item = VideoProductVideos::where('status', 1)
            ->where('check',1)
            ->where('text_status',3)
            ->orderRand()->findOrEmpty();
        if (!$item->isEmpty()) {

            $item->status = 2;
            $item->get_time = date('Y-m-d H:i:s');
            $item->save();
            return writeJson(200, $item, '素材获取');
        }

        return writeJson(200, null, '素材获取');
    }


    public function rewriteVideo(Request $request){

        $params = $request->post();

        $result = VideoProductVideos::where('id',$params["id"])->findOrEmpty();

        if (!$result->isEmpty()) {

            if (isset($params["position"]) && !empty($params["position"])) {
                $params["has_position"] = 1;
            }
            if (isset($params["check"]) && !empty($params["check"])) {
                $uid = LoginToken::getInstance()->getCurrentUid();
                $params["uid"] = $uid;
            }
            $result->save($params);
        }
        return  writeJson(200, $result, '回填商品视频');
    }

    public function addMaterial(Request $request)
    {
        $params = $request->post();
        $data = json_decode($params["data"], true);
        $count = 0;
        if (count($data) > 0) {
            foreach ($data as $video) {
                $count++;
                VideoProductMaterial::create($video);

            }
        }
        return writeJson(200, $count, '上传素材视频');
    }
    public function productList(Request $request)
    {
        $params = $request->get();
        $pids = [];
        $list_query = VideoProduct::field("id,douyin_pid,douyin_pname,jd_pid,category,tag,live_url");
        if (isset($params["douyin_pname"]) && !empty($params["douyin_pname"])) {
            $list_query = $list_query->whereLike("douyin_pname", "%".$params["douyin_pname"]."%");
        }
        if (isset($params["douyin_pid"]) && !empty($params["douyin_pid"])) {
            $list_query = $list_query->where("douyin_pid", $params["douyin_pid"]);
        }

        $list = $list_query->select()->toArray();
        if (!empty($list)) {
            foreach ($list as $key=>$li) {
                $list[$key]["count"] = 0;
                $pids[] = $li["douyin_pid"];
            }
        }
        $counts_query = VideoProductMaterial::field("douyin_pid,count(*) c")
            ->whereIn("douyin_pid", $pids);
        if ($params["platform"] == "douyin") {
            $counts_query = $counts_query->where("use_num", "<", 2);
        } elseif($params["platform"] == "jd") {
            $counts_query = $counts_query->where("jd_use_num", "<", 2);
        }
        $counts = $counts_query->group("douyin_pid")->select()->toArray();

        foreach ($list as $key=>$val) {
            foreach ($counts as $count) {
                if ($val["douyin_pid"] == $count["douyin_pid"]) {
                    $list[$key]["count"] = $count["c"];
                }
            }
        }
        return  writeJson(200, $list, '商品列表');
    }

    public function getProductMaterial(Request $request)
    {
        // 抖音视频换一换
        $params = $request->get();

        $list_query = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])
            ->where("use_num", "<", 2)
            ->limit(10)
            ->orderRand();
        if (!empty($params["ids"])) {
            $ids = explode(",", $params["ids"]);
            $list_query = $list_query->whereNotIn("id", $ids);
        }
        $list = $list_query->select()->toArray();

        return  writeJson(200, $list, '素材列表');
    }

    public function getProduct()
    {
        $list = VideoProduct::field("id,douyin_pid")->select()->toArray();
        return  writeJson(200, $list, '素材列表');
    }

    public function signUseNum(Request $request)
    {
        $params = $request->get();
        $res = VideoProductMaterial::where("id", $params["id"])->setInc('use_num');
        return  writeJson(200, $res, '更新使用次数');
    }

    public function aiText(Request $request)
    {
        $params = $request->post();
        $nums = json_decode($params["nums"], true);

        $product = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();
        $count = VideoProductVideos::where("text_status", 3)
            ->where("douyin_pid", $params["douyin_pid"])
            ->where("text", "<>", "")->count();
        if ($count >= 5) {
            $texts = VideoProductVideos::where("text_status", 3)
                ->where("douyin_pid", $params["douyin_pid"])
                ->where("text", "<>", "")
                ->limit(3)->orderRand()->select()->toArray();

            $res = (new Doubao())->aiText($product["douyin_pname"],$nums, $texts);

            return  writeJson(200, $res, '视频字幕');
        } else {
            return  writeJson(200, $params["douyin_pid"], '参考素材不足');
        }
    }

    public function aiTextNew(Request $request)
    {
        $params = $request->post();
        $nums = json_decode($params["nums"], true);
        $platform = $params["platform"]??"jd";
        $count = VideoProductVideos::where("text_status", 3)
            ->where("douyin_pid", $params["douyin_pid"])
            ->where("text", "<>", "")->count();
        if ($count >= 5) {
            $texts = VideoProductVideos::where("text_status", 3)
                ->where("douyin_pid", $params["douyin_pid"])
                ->where("text", "<>", "")
                ->limit(3)->orderRand()->select()->toArray();

            $res = (new Doubao())->aiTextNew($nums, $texts, $platform);

            return  writeJson(200, $res, '视频字幕');
        } else {
            return  writeJson(200, $params["douyin_pid"], '参考素材不足');
        }
    }

    public function aiTextJd(Request $request)
    {
        $params = $request->post();
//        $nums = json_decode($params["nums"], true);

        $product = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();

        $texts = VideoProductMaterial::field("text,CHAR_LENGTH(text) num")
            ->where("use_num", "<", 3)
            ->where("douyin_pid", $params["douyin_pid"])
            ->whereNotNull("text")
            ->limit(7)->orderRand()->select()->toArray();

        dump($texts);
        $res = (new Doubao())->aiTextJd($product["douyin_pname"], $texts);
//        $res["origin"] = [];
//        foreach ($texts as $text) {
//            $res["origin"][] = $text;
//        }

        return  writeJson(200, $res, '京东视频字幕');

    }

    public function delQiniu($bucketName, $key)
    {
        // 初始化七牛服务
        $qiniu = new Qiniu($bucketName);
        $res = $qiniu->deleteFile($key);

        return  writeJson(200, $res["success"], '七牛线上删除');
    }

    public function delQiniuBatch($bucketName, $key)
    {
        // 初始化七牛服务
        $qiniu = new Qiniu($bucketName);
        $res = $qiniu->deleteFileBatch($key);

        return  writeJson(200, $res["success"], '七牛线上删除');
    }

    public function uploadFile(Request $request)
    {
        $params = $request->post();
        $file = $request->file('file');

        $qiniu = new Qiniu($params["bucketName"]);
        $res = $qiniu->uploadFile($file);
        return  writeJson(200, $res, '七牛上传');

    }

    public function jdPull(Request $request)
    {
        $params = $request->get();
        $limit = $params["limit"]??42;
        //检查 jd_pid tb_pid
        $product = VideoProduct::where("douyin_pid", $params['douyin_pid'])->findOrEmpty();
        if (empty($product["jd_pid"]) && empty($product["tb_pid"])) {
            return  writeJson(200, [], '没有京东id并且没有淘宝id,不可做');
        }
        $material = VideoProductMaterial::where("douyin_pid", $params['douyin_pid'])
            ->whereNull("delete_time")
            ->where("jd_use_num", "<",2)
            ->limit($limit)
            ->orderRand()->select()->toArray();
        return  writeJson(200, $material, '京东拉取');
    }

    public function dyPull(Request $request)
    {
        $params = $request->get();
        $limit = $params["limit"]??2;
        $material = VideoProductMaterial::where("douyin_pid", $params['douyin_pid'])
            ->whereNull("delete_time")
            ->where("use_num", "<",3)
            ->limit($limit)
            ->orderRand()->select()->toArray();
        return  writeJson(200, $material, '抖音拉取');
    }

    public function exchangeOne(Request $request)
    {
        $params = $request->post();

        $del_material = VideoProductMaterial::where("id", $params["id"])->findOrEmpty();

        $material = VideoProductMaterial::where("douyin_pid", $del_material['douyin_pid'])
            ->where("jd_use_num", "<",2)
            ->whereNotIn("id", $params["ids"])
            ->orderRand()->findOrEmpty();

//        // 七牛云删除
//        $this->delQiniu("guang1121", str_replace("http://yaoyao.youdnr.cn/", "", $del_material["url"]));
//        // 数据库删除
//        $del_material->delete();

        $del_material->delete_time = date('Y-m-d H:i:s');
        $del_material->save();

        return  writeJson(200, $material, '换一条');
    }

    public function jdPull1(Request $request)
    {
        $params = $request->get();
        $pids = [];
        $real_usefel_data = [];
        $products = [];
        // 是否有传产品
        // 统计可用素材 随机取3个 按id排序
        $useful_data_query = VideoProductMaterial::field("douyin_pid, count(*) c")
            ->where("jd_use_num", "<",2);
        if (isset($params["pname"]) && !empty($params["pname"])) {
            $products = VideoProduct::field("douyin_pid,douyin_pname,jd_pid,category")
                ->whereLike("douyin_pname", "%".$params['pname']."%")
                ->select()->toArray();
            if (!empty($products)) {
                foreach ($products as $p) {
                    $pids[] = $p["douyin_pid"];
                    $useful_data_query = $useful_data_query->whereIn("douyin_pid", $pids);
                }
            }
        }
        $useful_data = $useful_data_query->group("douyin_pid")->select()->toArray();

        //把素材量小于7的过滤掉
        if (!empty($useful_data)) {
            foreach ($useful_data as $val) {
                if ($val["c"] >= 7) {
                    $real_usefel_data[] = $val;
                }
            }
        }
        if (!empty($real_usefel_data)) {
            $randomKeys = array_rand($real_usefel_data, min(3, count($real_usefel_data)));
            // 确保总是返回数组形式（当只取1个时array_rand返回单个值）
            if (!is_array($randomKeys)) {
                $randomKeys = [$randomKeys];
            }
            // 根据键名提取对应的值
            $randomPids = [];
            $randomValues = array_map(function($key) use ($real_usefel_data) {
                return $real_usefel_data[$key];
            }, $randomKeys);

            // 如果没有指定产品
            if (!isset($params["pname"]) || empty($params["pname"])) {
                foreach ($randomValues as $val) {
                    $randomPids[] = $val["douyin_pid"];
                }
                $products = VideoProduct::field("douyin_pid,douyin_pname,jd_pid,category")
                    ->whereIn("douyin_pid", $randomPids)
                    ->select()->toArray();
            }


            //开始拿素材
            $result = [];
            $min = 7;
            foreach ($randomValues as $val) {
                $item = [];
                $max = 10;
                if ($val["c"] < 10) {
                    $max = $val["c"];
                }
                //确定要拿几段素材
                $randomNumber = rand($min, $max);
                //真正获取素材
                $material = VideoProductMaterial::where("douyin_pid", $val["douyin_pid"])
                    ->where("jd_use_num", "<",2)
                    ->limit($randomNumber)
                    ->orderRand()->select()->toArray();
                usort($material, function($a, $b) {
                    return $a['id'] <=> $b['id']; // 使用太空船操作符进行倒序比较
                });
                $item["material"] = $material;
                //products中 找到具体商品信息
                foreach ($products as $p) {
                    if ($val["douyin_pid"] == $p["douyin_pid"]) {
                        $item["douyin_pid"] = $val["douyin_pid"];
                        $item["douyin_pname"] = $p["douyin_pname"];
                        $item["jd_pid"] = $p["jd_pid"];
                        $item["category"] = $p["category"];
                    }
                }
                $result[] = $item;
            }
            return  writeJson(200, $result, '京东拉取');
        }
    }

    public function addEvent(Request $request) {
        $params = $request->post();
        $data = json_decode($params["data"], true);
        $event = new  VideoEvent();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $username = LoginToken::getInstance()->getCurrentUserName();



        $yx_list = Config::where("name", "guang_yx")->select()->toArray();
        $bgm_list = Config::where("name", "guang_bgm")->select()->toArray();
        $num = 0;
        DB::startTrans();
        try {
            foreach ($data as $keyda=>$da) {
                // 标题敏感词
                if (strpos($da["title"], "清仓") !== false) {
                    throw new Exception("视频" . ($keyda + 1) . ",标题含有敏感词-清仓");
                }
                // 检查标题重复性
                $info = VideoEvent::where("title", $da["title"])->findOrEmpty();
                if (!$info->isEmpty()) {
                    throw new Exception("标题{$da["title"]}有重复性，请修改后提交");
                }

                $item = [];
                $item["uid"] = $uid;
                $item['title'] = str_replace(";", "", str_replace("；", "", $da["title"]));
//                $item['jd_pid'] = $da["jd_pid"]??null;
                $item['douyin_pid'] = $da["douyin_pid"];
                $item['douyin_pname'] = $da["douyin_pname"];
//                $item['category'] = $da["category"];
                $item['model'] = $username;
                $item['status'] = 1;
                $item["zimu_site"] = 15;
                $item["zimu_size"] = 10;
                $item["zimu_style"] = "style1";
                $item["is_kou"] = 0;
                // todo
                $project = VideoProduct::where("douyin_pid", $da["douyin_pid"])->findOrEmpty();
                $item['category'] = $project["category"];
                $item['jd_pid'] = $project["jd_pid"];
                $item['tb_pid'] = $project["tb_pid"];

                $script_arr = json_decode($da["script"], true);

                foreach ($script_arr as $key=>$val) {
                    if (strpos($val["text"], "直播") !== false) {
                        throw new Exception("视频" . ($keyda + 1) . ",字幕" . ($key + 1) . "含有敏感词-直播");
                    }
                    $script_arr[$key]["text"] = str_replace("、", ",", $val["text"]);

                    if (!isset($val["yx"])) {
                        $script_arr[$key]["yx"] = "";
                    }
                    //字幕坐标
                    $m_info = VideoProductMaterial::where("id", $val["m_id"])->findOrEmpty();
                    $video_info = VideoProductVideos::where("id", $m_info["vid"])->findOrEmpty();
                    $script_arr[$key]["position"] = null;
                    if (!empty($video_info["position"])) {
                        $script_arr[$key]["position"] = $video_info["position"];
                    }

                    // 更新使用次数
                    $res = VideoProductMaterial::where("id", $val["m_id"])->setInc('jd_use_num');
                }
                //随机分配一个bgm
                $item["bgm"] = $bgm_list[array_rand($bgm_list)]["value"];
//                // 随机取两个镜头加音效
//                $randomKeys = array_rand($script_arr, 2);
//                foreach ($randomKeys as $key) {
//                    $script_arr[$key]["yx"] = $yx_list[array_rand($yx_list)]["value"];
//                }
                //随机分配一个声音
                $voice = LiveVoice::whereNotNull('boba_voice')->orderRand()->find();
                $item["sound_model"] = $voice["boba_voice"];

                $item["script"] = json_encode($script_arr, JSON_UNESCAPED_SLASHES  | JSON_UNESCAPED_UNICODE);
                $new = $event->create($item);
                $num++;
            }


            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,$e->getMessage());
        }
        return writeJson(200, $num, '请求成功');
    }

    public function getVideoEvent(Request $request) {
        $event = new VideoEvent();
        $info_query = $event->where("status", 1)
            ->where("is_top", 1)
            ->where(function ($q){
                $ten_min_ago = date("Y-m-d H:i:s", time() - 300);
                $q->whereNull('get_time')->whereOr('get_time','<',$ten_min_ago);
            });
        $info = $info_query->findOrEmpty();
        if ($info->isEmpty()) {
            $info_query = $info_query->removeWhereField("is_top");
            $info = $info_query->findOrEmpty();
        }

        if (!$info->isEmpty()) {
            //检查有没有分配声音
            if (empty($info["sound_model"])) {
                $voice = LiveVoice::whereNotNull('boba_voice')->orderRand()->find();
                $info->sound_model = $voice["boba_voice"];
            }
                // 检查是否有jdpid tbpid
            if (empty($info["jd_pid"]) && empty($info["tb_pid"])) {
                $info->status = 4;
                $info->reason = "没有京东id并且没有淘宝id";
                $info->save();
                return writeJson(200, [], '请求成功');
            } else {
                $info->status = 2;
                $info->get_time = date("Y-m-d H:i:s", time());
                $info->save();
                return writeJson(200, $info, '请求成功');
            }

        } else {
            return writeJson(200, [], '无');
        }
    }

    public function backfillEvent(Request $request)
    {
        $params = $request->post();
        $info = VideoEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            if (isset($params["status"]) && $params["status"] == 3) {
                $params["check"] = 1;
                $params["check_uid"] = 1;
            }
            //视频处理失败原因为 视频 太短 自动换个声音重跑
            if (isset($params["status"]) && $params["status"] == 4 &&
                isset($params["reason"]) && strpos($params["reason"], "太短") !== false) {
                $voice = LiveVoice::whereNotNull('boba_voice')->where("boba_voice", "<>", $info["sound_model"])->orderRand()->find();
                $params["sound_model"] = $voice["boba_voice"];
                $params["status"] = 1;
                $params["get_time"] = null;
            }
            $info->save($params);
            return writeJson(200,$info,'成功！');
        } else {
            return writeJson(400,[],'找不到！');
        }
    }

    public function batchCheck(Request $request){
        $params = $request->patch();
        $event = new VideoEvent();
        $ids = $params['ids'];
        $uid = LoginToken::getInstance()->getCurrentUid();

        $result = $event->whereIn('id',$ids)
            ->where("status", 3)->update([
            'check' => 1,
            'check_uid' => $uid,
            'check_time' => date("Y-m-d H:i:s")
        ]);
        return writeJson(200,$result,'批量检查！');
    }

    public function checkUseless(Request $request)
    {
        $params = $request->post();
        $event = new VideoEvent();
        $uid = LoginToken::getInstance()->getCurrentUid();

        DB::startTrans();
        try {
            $info = $event->where("id", $params["id"])
                ->findOrEmpty();
            if (!$info->isEmpty()) {
                $info->status = 24;
                $info->check_uid = $uid;
                $info->check_time = date("Y-m-d H:i:s");
                $info->save();
            }

            // 素材恢复
//            $script = json_decode($info["script"], true);
//            foreach ($script as $s) {
//                VideoProductMaterial::where("id", $s["m_id"])
//                    ->setDec('jd_use_num');
//            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e, '请求失败');
        }

        return writeJson(200,$info,'弃用！');
    }

    public function list(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $event = new VideoEvent();

        $query = $event->field("*");

        if ($uid != 1 && $uid != 85 && $uid != 32 && $uid != 71 && $uid != 72) {
            $query = $query->where("uid", $uid);
        }
        if (!empty($params["jd_pid"])) {
            $query = $query->where("jd_pid", $params["jd_pid"]);
        }
        if (!empty($params["douyin_pid"])) {
            $query = $query->where("douyin_pid", $params["douyin_pid"]);
        }
        if (!empty($params["douyin_pname"])) {
            $query = $query->whereLike("douyin_pname", "%".$params["douyin_pname"]."%");
        }
        if (!empty($params["model"])) {
            $query = $query->where("model", $params["model"]);
        }
        if (!empty($params["title"])) {
            $query = $query->where("title", $params["title"]);
        }
        if (isset($params["check"])) {
            $query = $query->where("check", $params["check"]);
        }
        if (!empty($params["status"])) {
            $query = $query->where("status", $params["status"]);
        }
        if (!empty($params["category"])) {
            $query = $query->where("category", $params["category"]);
        }
//        if (!empty($params["secondary"])) {
//            $query = $query->where("b.secondary", $params["secondary"]);
//        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("create_time", "<", $params["end_time"]);
        }
        if (isset($params["jd_export"]) && $params["jd_export"] !== "") {
            if ($params["jd_export"] == 1) {
                $query = $query->where("jd_export", 1);
            } else if ($params["jd_export"] == 0) {
                $query = $query->whereNull("jd_export");
            }
        }
        if (isset($params["tb_export"]) && $params["tb_export"] !== "") {
            if ($params["tb_export"] == 1) {
                $query = $query->where("tb_export", 1);
            } else if ($params["tb_export"] == 0) {
                $query = $query->whereNull("tb_export");
            }
        }

        $list = $query->order("id desc")->paginate($pageSize);

        $check_uids = [];
        if (!empty($list)) {
            foreach ($list as $li) {
                $check_uids[] = $li["check_uid"];
            }
            $user = LinUser::whereIn("id", $check_uids)->select()->toArray();
            foreach ($list as $key=>$val) {
                foreach ($user as $u) {
                    if ($val["check_uid"] == $u["id"]) {
                        $list[$key]["check_name"] = $u["username"];
                    }
                }
            }
        }
        return writeJson(200,$list,'数据列表！');

    }

    public function getListById(Request $request)
    {
        $params = $request->get();
        $fifteenDaysAgo = strtotime('-15 days', time());
        $two_hour_ago = date("Y-m-d H:i:s", time() - 3600);

        DB::startTrans();
        try {
            $cur_group = [];
            $event = new VideoEvent();
            $uid = LoginToken::getInstance()->getCurrentUid();
            $video_download_group = Config::where("name", "video_download_group")->select()->toArray();
            foreach ($video_download_group as $group) {
                if (in_array($uid, json_decode($group["value"], true))) {
                    $cur_group = json_decode($group["value"], true);
                    break;
                }
            }
            if (!isset($params["jd"]) || !isset($params["tb"])) {
                throw new Exception("请更换新版本插件");
            }
            if (empty($cur_group)) {
                throw new Exception("账号未分组");
            }
            if (!isset($params["category"])) {
                throw new Exception("未选择分类");
            }
            if (!isset($params["limit"])) {
                throw new Exception("未选择数量");
            }

            $list_query = $event->where("status", 3)
                ->where("check", 1)
                ->whereIn("uid", $cur_group);
            if ($params["jd"] == "是") {
                $list_query = $list_query->where('jd_pid', 'not null')
                    ->where('jd_export', 'null')
                    ->where(function ($q) use ($two_hour_ago){
                        $q->whereNull('jd_get_time')->whereOr('jd_get_time','<',$two_hour_ago);
                    });
            } else if ($params["tb"] == "是") {
                $list_query = $list_query->where('tb_pid', 'not null')
                    ->where('tb_export', 'null')
                    ->where(function ($q) use ($two_hour_ago){
                        $q->whereNull('tb_get_time')->whereOr('tb_get_time','<',$two_hour_ago);
                    });
            }
            $list_query = $list_query->where("get_time", ">=", date('Y-m-d H:i:s', strtotime('midnight', $fifteenDaysAgo)));
            if ($params["category"] != "") {
                $category_arr = explode(",", $params["category"]);
                $list_query = $list_query->whereIn("category", $category_arr);
            }
            if ($params["limit"] != 0) {
                $list_query = $list_query->limit($params["limit"]);
            }
            $list = $list_query->lock()->select()->toArray();

            // 被领取到的 先标记时间 并检查标题重复性
            $titles = [];
            $savedata = [];
            if (!empty($list)) {
                foreach ($list as $li) {
                    $item = [];
                    $item["id"] = $li["id"];
                    if (in_array($li["title"], $titles)) {
                        $item["same_title"] = 1;
                    } else {
                        $titles[] = $li["title"];
                        $item["same_title"] = 0;
                        if ($params["jd"] == "是" && $li["jd_export"] == null) {
                            $item["jd_get_time"] = date("Y-m-d H:i:s");
                        } else if ($params["tb"] == "是" && $li["tb_export"] == null) {
                            $item["tb_get_time"] = date("Y-m-d H:i:s");
                        }
                    }

                    $savedata[] = $item;
                }
                $res = $event->saveall($savedata);
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e->getMessage(), '请求失败');
        }

        return writeJson(200, $list, '请求成功');

    }

    public function backfillDownload(Request $request)
    {
        $params = $request->post();
        $ids = json_decode($params["ids"], true);
        $savedata = [];
        $flag = 0;
        $event = new VideoEvent();
        $list = $event->whereIn("id", $ids)->select()->toArray();
        foreach ($list as $li) {
            $flag = 0;
            $item = [];
            $item["id"] = $li["id"];
            $item["jd_export"] = $li["jd_export"];
            $item["tb_export"] = $li["tb_export"];
            if ($li["jd_export"] == 2) {
                $item["jd_export"] = null;
                $flag = 1;
            }
            if ($li["tb_export"] == 2) {
                $item["tb_export"] = null;
                $flag = 1;
            }
            if ($flag) {
                $savedata[] = $item;
            }
        }
        if (!empty($savedata)) {
            $res = $event->saveall($savedata);
        }
        return writeJson(200, $res, '请求成功');
    }

    public function getMaterialNum(Request $request)
    {
        $params = $request->get();
        $pageSize = $params['pageSize'] ?? 50;
        $platform = $params["platform"]??"douyin";


        $query = VideoProduct::field("*");
        if (!empty($params["douyin_pid"])) {
            $query = $query->where("douyin_pid", $params["douyin_pid"]);
        }
        if (!empty($params["douyin_pname"])) {
            $query = $query->whereLike("douyin_pname", "%".$params["douyin_pname"]."%");
        }
        if (!empty($params["jd_pid"])) {
            $query = $query->where("jd_pid", $params["jd_pid"]);
        }
        if (!empty($params["tb_pid"])) {
            $query = $query->where("tb_pid", $params["tb_pid"]);
        }
        if (!empty($params["category"])) {
            $query = $query->where("category", $params["category"]);
        }
        if (!empty($params["pro_type"])) {
            $query = $query->where("pro_type", $params["pro_type"]);
        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">=", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("create_time", "<", $params["end_time"]);
        }
        if (!empty($params["min_num"])) {
            $query = $query->where("suc_num", ">=", $params["min_num"]);
        }
        if (!empty($params["max_num"])) {
            $query = $query->where("suc_num", "<", $params["max_num"]);
        }
        if (!empty($params["min_export"])) {
            $query = $query->where("export_num", ">=", $params["min_export"]);
        }
        if (!empty($params["max_export"])) {
            $query = $query->where("export_num", "<", $params["max_export"]);
        }
        if ($platform == "douyin") {
            $list = $query->order("material_num desc")->paginate($pageSize);
        } else {
            $query = $query->whereIn("pro_type", ["共用","京东产品"]);

            $list = $query->order("jd_material_num desc")->paginate($pageSize);
        }

        return writeJson(200, $list, '请求成功');
    }

    public function export(Request $request)
    {
        $params = $request->get();

        DB::startTrans();
        try {
            $query = VideoProduct::field("id,douyin_pname,category,material_num,video_num,douyin_pid,jd_pid,tb_pid,pro_type,create_time");
            if (!empty($params["douyin_pid"])) {
                $query = $query->where("douyin_pid", $params["douyin_pid"]);
            }
            if (!empty($params["douyin_pname"])) {
                $query = $query->where("douyin_pname", "%".$params["douyin_pname"]."%");
            }
            if (!empty($params["jd_pid"])) {
                $query = $query->where("jd_pid", $params["jd_pid"]);
            }
            if (!empty($params["tb_pid"])) {
                $query = $query->where("tb_pid", $params["tb_pid"]);
            }
            if (!empty($params["category"])) {
                $query = $query->where("category", $params["category"]);
            }
            if (!empty($params["pro_type"])) {
                $query = $query->where("pro_type", $params["pro_type"]);
            }
            if (!empty($params["start_time"])) {
                $query = $query->where("create_time", ">=", $params["start_time"]);
            }
            if (!empty($params["end_time"])) {
                $query = $query->where("create_time", "<", $params["end_time"]);
            }
            $list = $query->order("material_num desc")->select()->toArray();

            if (!empty($list)) {
                $data = [];

                foreach ($list as $li) {
                    $add = [];

                    $add["id"] = $li["id"];
                    $add["douyin_pid"] = $li["douyin_pid"];
                    $add["douyin_pname"] = $li["douyin_pname"];
                    $add["category"] = $li["category"];
                    $add["material_num"] = $li["material_num"];
                    $add["video_num"] = $li["video_num"];
                    $add["jd_pid"] = $li["jd_pid"];
                    $add["tb_pid"] = $li["tb_pid"];
                    $add["pro_type"] = $li["pro_type"];
                    $add["create_time"] = $li["create_time"];
                    $data[] = $add;
                }

                $xlsName = date('Ymd')."_商品列表导出"; // 表名称
                $xlsCell = [
                    ['id', 'id'],
                    ['douyin_pid', '抖音产品id'],
                    ['douyin_pname', '抖音产品名称'],
                    ['category', '分类'],
                    ['material_num', '素材量'],
                    ['video_num', '脚本量'],
                    ['jd_pid', '京东商品id'],
                    ['tb_pid', '淘宝商品id'],
                    ['pro_type', '商品类型'],
                    ['create_time', '创建时间'],
                ];// 表头信息

//                dump($data);
                $this->downloadExcel($xlsName, $xlsCell, $data);// 传递参数

            } else {
                return writeJson(200, 0, '暂无数据');
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e->getMessage(), '请求失败');
        }
        return writeJson(200, count($data), '请求成功');
    }

    public function downloadExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle    = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $cellNum     = count($expCellName);// 单元格长度
        $dataNum     = count($expTableData);
        $objPHPExcel = new \PHPExcel();// 引入库
        $cellName = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
        }

        // Miscellaneous glyphs, UTF-8  循环写入数据
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                if ($j == 1 || $j == 6 || $j == 7) {
                    $objPHPExcel->getActiveSheet(0)
                        ->setCellValue($cellName[$j] . ($i + 2), " ".(string)$expTableData[$i][$expCellName[$j][0]]);
                } else {
                    $objPHPExcel->getActiveSheet(0)
                        ->setCellValue($cellName[$j] . ($i + 2), (string)$expTableData[$i][$expCellName[$j][0]]);
                }
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");//创建生成的格式
        header('Content-Disposition: attachment;filename="'.$xlsTitle.'.xlsx"');//下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        return $PHPWriter->save('php://output');
    }
    /*
     * 更新商品素材量、视频量
     */
    public function updateMaterialNum(Request $request)
    {
        $params = $request->get();
        $info = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();
        if (!empty($info)) {
            //入库视频量
            $all_videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])->count();
            //入库视频 待采集字幕量
            $wait_videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])
                ->where(function ($q){
                    $q->where('text_status', 1)->whereOr('text_status', 2);
                })
                ->count();
            //入库视频 待采集字幕量
            $fail_videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])
                ->where("text_status", 4)
                ->count();
            //入库视频 已生成字幕量
            $videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])
                ->where("text_status", 3)
                ->count();
            //切片量
            $material = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])
                ->whereNull("delete_time")
//                ->where("jd_use_num", "<", 5)
                ->where("use_num", "<", 3)
                ->count();
            $jd_material = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])
                ->whereNull("delete_time")
                ->where("jd_use_num", "<", 2)
//                ->where("use_num", "<", 3)
                ->count();
            //待标注视频量
            $wait_pull = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])
                ->where("check",0)
                ->where("text_status", 3)
                ->count();
            //成功合成视频
            $suc_num = VideoEvent::where("douyin_pid", $params["douyin_pid"])
                ->where("status", 3)
                ->count();
            //商品下视频下载次数
            $export_num = ChimiEvent::where("pid", $params["douyin_pid"])
                ->where("dy_export", 1)
                ->count();
            //原素材审核不通过数量
            $check4_num = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])
                ->where("check", 4)
                ->count();

            $info->video_num = $videos;
            $info->material_num = $material;
            $info->jd_material_num = $jd_material;
            $info->all_video = $all_videos;
            $info->wait_video = $wait_videos;
            $info->fail_video = $fail_videos;
            $info->wait_pull = $wait_pull;
            $info->suc_num = $suc_num;
            $info->export_num = $export_num;
            $info->check4_num = $check4_num;
            $info->save();
        }
        return writeJson(200, true, "{$params["douyin_pid"]}->ma:{$material}->video:{$videos}");
    }
    public function updateProject(Request $request)
    {
        $params = $request->post();
        DB::startTrans();
        try {

            $project = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();
            if (!$project->isEmpty()) {
                $jd_pid = empty($params['jd_pid'])?null:$params['jd_pid'];
                $tb_pid = empty($params['tb_pid'])?null:$params['tb_pid'];
                $category = empty($params['category'])?null:$params['category'];
                $pro_type = empty($params['pro_type'])?null:$params['pro_type'];
                $live_url = empty($params['live_url'])?null:$params['live_url'];
                $project->jd_pid = $jd_pid;
                $project->tb_pid = $tb_pid;
                $project->category = $category;
                $project->pro_type = $pro_type;
                $project->live_url = $live_url;

                $project->save();


                $res = VideoEvent::where("douyin_pid", $params["douyin_pid"])
                    ->whereNull("jd_export")
                    ->whereNull("tb_export")
                    ->update([
                        "jd_pid"=>$jd_pid,
                        "tb_pid"=>$tb_pid,
                        "category"=>$category,
                        "pro_type"=>$pro_type
                    ]);
                if (!empty($params['live_url'])) {
                    $res = ChimiEvent::where("pid", $params["douyin_pid"])
                        ->whereNull("dy_export")
                        ->update([
                            "live_url"=>$live_url
                        ]);
                }
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e->getMessage(), '请求失败');
        }
        return writeJson(200, $res, '请求成功');

    }

    public function getTextEvent(Request $request)
    {
        $params = $request->get();
        DB::startTrans();
        try {
            $info_query = VideoProductVideos::where("text_status", 1);
            if (isset($params["douyin_pid"]) && !empty($params["douyin_pid"])) {
                $info_query = $info_query->where("douyin_pid", $params["douyin_pid"]);
            }
            $info = $info_query->orderRand()->lock()->findOrEmpty();
            if (!$info->isEmpty()) {
                $info->text_status = 2;
                $info->save();
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e->getMessage(), '请求失败');
        }
        return writeJson(200, $info, '请求成功');
    }

    public function backfillTextEvent(Request $request)
    {
        $params = $request->post();
        $info = VideoProductVideos::where("content_id", $params["content_id"])->findOrEmpty();
        $text = "";
        if (!$info->isEmpty()) {
            $info->text_status = $params["status"];
            if (isset($params["reason"]) && !empty($params["reason"])) {
                $info->reason = $params["reason"];
            }
            if (isset($params["content_text"]) && !empty($params["content_text"])) {
                foreach ($params["content_text"] as $val) {
                    $text = $text.$val["text"];
                }
                $info->text = $text;
                $info->split = json_encode($params["content_text"],JSON_UNESCAPED_UNICODE |JSON_UNESCAPED_SLASHES);
            }
            $res = $info->save();
        }
        return writeJson(200, $res, '请求成功');
    }

    public function videosList(Request $request)
    {
        $params = $request->post();
        $pageSize = $params['pageSize'] ?? 50;

        $query = VideoProductVideos::field("*");
        if (!empty($params["username"])) {
            $user = LinUser::where("username", $params["username"])->findOrEmpty();
            if (!$user->isEmpty()) {
                $query = $query->where("uid", $user["id"]);
            }
        }
        if (!empty($params["douyin_pid"])) {
            $query = $query->where("douyin_pid", $params["douyin_pid"]);
        }
        if (!empty($params["douyin_pname"])) {
            $query = $query->whereLike("douyin_pname", "%".$params["douyin_pname"]."%");
        }
        if (isset($params["check"])) {
            $query = $query->where("check", $params["check"]);
            if ($params["check"] == 0) {
                $query = $query->where("text_status", 3);
            }
        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("create_time", "<", $params["end_time"]);
        }
        $list = $query->order("id desc")->paginate($pageSize);

        $uids = [];
        foreach ($list as $li) {
            $uids[] = $li["uid"];
        }
        $users = LinUser::field("id,username")->whereIn("id", $uids)->select()->toArray();
        foreach ($list as $key=>$li) {
            foreach ($users as $u) {
                if ($li["uid"] == $u["id"]) {
                    $list[$key]["username"] = $u["username"];
                }
            }
        }

        return writeJson(200,$list,'数据列表！');
    }

    public function videosPull(Request $request)
    {
        $params = $request->get();

        DB::startTrans();
        try {
            $item_query = VideoProductVideos::where("status", 1)
                ->where("check", 0)
                ->where("text_status", 3)
                ->where(function ($q){
                    $ten_min_ago = date("Y-m-d H:i:s", time() - 600);
                    $q->whereNull('get_time')->whereOr('get_time','<',$ten_min_ago);
                });
            if (isset($params["douyin_pid"]) && !empty($params["douyin_pid"])) {
                $item_query = $item_query->where("douyin_pid", $params["douyin_pid"]);
            }
            $item = $item_query->orderRand()->lock()->findOrEmpty();
            if (!$item->isEmpty()) {
                $item->uid = LoginToken::getInstance()->getCurrentUid();
                $item->get_time = date('Y-m-d H:i:s');
                $item->save();
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,$e->getMessage());
        }
        return writeJson(200, $item, '请求成功');

    }

    public function tbCount()
    {
        $result = [];
        $list = Config::where("name", "tbfilename")->select()->toArray();
        foreach ($list as $li) {
            $item = [];
            $item["category"] = $li["key"];
            $item["account"] = $li["value"];
            $item["pids"] = 0;
            $result[] = $item;
        }
        // 查询今日tb导出了多少
        $events = VideoEvent::field("tb_account, category, douyin_pid")
            ->where("status", 3)
            ->where("tb_backtime", ">=", date('Y-m-d H:i:s'))
            ->select()->toArray();

        foreach ($events as $event) {
            foreach ($result as $key=>$re) {
                if ($event["tb_account"] == $re["account"] && $event["category"] == $re["category"]) {
                    $result[$key]["pids"][] = $event["douyin_pid"];
                }
            }
        }
        return writeJson(200, $result, '请求成功');
    }

    public function addProduct(Request $request)
    {
        $params = $request->post();
        $info = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();
        if (!$info->isEmpty()) {
            return writeJson(200, false, '商品已存在');
        }
        $video = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])->count();
        $add = [];
        $add["douyin_pid"] = $params['douyin_pid'];
        $add["douyin_pname"] = $params['douyin_pname'];
        $add["douyin_purl"] = $params['douyin_purl'];
        $add["category"] = $params['category'];
        $add["pro_type"] = $params['pro_type'];
        $add["cover"] = !empty($params['cover']) ? $params['cover']:'';
        if ($video == 0) {
            $add["status"] = 1;
        }
        $add["cr"] = $params['cr']??null;
        // 新增商品
        $res = VideoProduct::create($add);
        return writeJson(200, $res, '添加成功');
    }




    public function getProductOne()
    {
        $info = VideoProduct::where("status", 1)->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->status = 2;
            $info->get_time = date('Y-m-d H:i:s');
            $info->save();
        }
        return writeJson(200, $info, '成功');
    }

    public function backfillProductOne(Request $request)
    {
        $params = $request->post();
        $info = VideoProduct::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->status = $params["status"];
            $info->reason = $params["reason"];
            $info->save();
        }
        return writeJson(200, $info, '商品状态回填');
    }

    public function addVideos(Request $request)
    {
        $params = $request->post();
        $data = json_decode($params["data"], true);
        $count = 0;
        foreach ($data as $da) {
            $is_exists = VideoProductVideos::where('content_id',$da['content_id'])->findOrEmpty();
            if($is_exists->isEmpty()){
                $count ++;
                VideoProductVideos::create($da);
            }
        }
        return writeJson(200, $count, '添加成功');
    }

    public function delCount(Request $request)
    {
        $params = $request->get();
        //有几个视频 有几个切片 有几条待生成的成品
        $videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])->count();
        $ma = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])->count();
        $event = VideoEvent::where("douyin_pid", $params["douyin_pid"])
            ->where(function ($q){
                $q->where('status', 1)->whereOr('status', 4);
            })->count();

        return writeJson(200, true, "有{$videos}个视频，{$ma}个切片，{$event}条待生成的成品,确定要删除吗？");
    }

    public function delProduct(Request $request)
    {
        $params = $request->get();
        $pro = 0;
        $videos = 0;
        $ma = 0;
        $event = 0;
        $keys = [];
        $ma_ids = [];
        //有几个视频 有几个切片 有几条待生成的成品
        DB::startTrans();
        try {
            $videos = VideoProductVideos::where("douyin_pid", $params["douyin_pid"])->delete();

            $ma_arr = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])
                ->limit(2000)->select()->toArray();

            foreach ($ma_arr as $val) {
                $ma_ids[] = $val["id"];
                $keys[] = str_replace("http://yaoyao.youdnr.cn/", "", $val["url"]);
            }
            // 七牛云删除
            $del_res = $this->delQiniuBatch("guang1121", $keys);
            if ($del_res->getData()["result"] == true) {
                $ma = VideoProductMaterial::where("douyin_pid", $params["douyin_pid"])
                    ->whereIn("id", $ma_ids)->delete();
                if (count($ma_arr) < 2000) {
                    $pro = VideoProduct::where("douyin_pid", $params["douyin_pid"])->delete();
                }
            }

            $event = VideoEvent::where("douyin_pid", $params["douyin_pid"])
                ->where(function ($q){
                    $q->where('status', 1)->whereOr('status', 4);
                })
                ->delete();


            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,$e->getMessage());
        }
        return writeJson(200, true, "删除{$pro}个商品，{$videos}个视频，{$ma}个切片，{$event}条待生成的成品");
    }

    public function updateEvent(Request $request)
    {
        $params = $request->get();

        $info = VideoEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->title = $params["title"];
            $info->save();
        }
        return writeJson(200, $info, '更新成功');

    }

    public function resetEvent(Request $request)
    {
        $params = $request->get();
        $info = VideoEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            if ($info["status"] == 4) {
                $info->status = 1;
                $info->reason = null;
            }
            $info->save();
        }
        return writeJson(200, true, '请求成功');
    }

    public function daily()
    {
        $uid = LoginToken::getInstance()->getCurrentUid();
        $yesterday = strtotime("-1 day");
        $yesterdaystart = date('Y-m-d 00:00:00', $yesterday);

        if ($uid == 1) {
            $video_download_group = Config::where("name", "video_download_group")->select()->toArray();

            //        昨日标注的视频总数：
//        今日标注的视频总数：
            $biaozhu_y = VideoProductVideos::where("check", "<>", 0)
                ->where("get_time", ">=", $yesterdaystart)
                ->where("get_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $biaozhu_t = VideoProductVideos::where("check", "<>", 0)
                ->where("get_time", ">=", date('Y-m-d 00:00:00'))
                ->count();

            $str = "昨日标注的视频总数：{$biaozhu_y}\n";
            $str .= "今日标注的视频总数：{$biaozhu_t}\n";

//        昨日生产视频总数
//        今日生产视频总数
            $create_y = VideoEvent::where("create_time", ">=", $yesterdaystart)
                ->where("create_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $str .= "\n昨日生产视频总数：{$create_y}\n";
            foreach ($video_download_group as $group) {
                $cur_group = json_decode($group["value"], true);
                $create_y = VideoEvent::where("create_time", ">=", $yesterdaystart)
                    ->whereIn("uid", $cur_group)
                    ->where("create_time", "<", date('Y-m-d 00:00:00'))
                    ->count();
                $str .= " -{$group['remark']}：{$create_y}\n";
            }
            $create_t = VideoEvent::where("create_time", ">=", date('Y-m-d 00:00:00'))
                ->count();
            $str .= "\n今日生产视频总数：{$create_t}\n";
            foreach ($video_download_group as $group) {
                $cur_group = json_decode($group["value"], true);
                $create_t = VideoEvent::where("create_time", ">=", date('Y-m-d 00:00:00'))
                    ->whereIn("uid", $cur_group)
                    ->count();
                $str .= " -{$group['remark']}：{$create_t}\n";
            }

//        昨日京东下载视频数
//        今日京东下载视频数
            $jd_export_y = VideoEvent::where("jd_export", 1)
                ->where("jd_backtime", ">=", $yesterdaystart)
                ->where("jd_backtime", "<", date('Y-m-d 00:00:00'))
                ->count();
            $str .= "\n昨日京东下载视频数：{$jd_export_y}\n";
            foreach ($video_download_group as $group) {
                $cur_group = json_decode($group["value"], true);
                $jd_export_y = VideoEvent::where("jd_export", 1)
                    ->whereIn("uid", $cur_group)
                    ->where("jd_backtime", ">=", $yesterdaystart)
                    ->where("jd_backtime", "<", date('Y-m-d 00:00:00'))
                    ->count();
                $str .= " -{$group['remark']}：{$jd_export_y}\n";
            }
            $jd_export_t = VideoEvent::where("jd_export", 1)
                ->where("jd_backtime", ">=", date('Y-m-d 00:00:00'))
                ->count();
            $str .= "\n今日京东下载视频数：{$jd_export_t}\n";
            foreach ($video_download_group as $group) {
                $cur_group = json_decode($group["value"], true);
                $jd_export_t = VideoEvent::where("jd_export", 1)
                    ->whereIn("uid", $cur_group)
                    ->where("jd_backtime", ">=", date('Y-m-d 00:00:00'))
                    ->count();
                $str .= " -{$group['remark']}：{$jd_export_t}\n";
            }
//        昨日淘宝下载视频数
//        今日淘宝下载视频数
            $tb_export_y = VideoEvent::where("tb_export", 1)
                ->where("tb_backtime", ">=", $yesterdaystart)
                ->where("tb_backtime", "<", date('Y-m-d 00:00:00'))
                ->count();
            $tb_export_t = VideoEvent::where("tb_export", 1)
                ->where("tb_backtime", ">=", date('Y-m-d 00:00:00'))
                ->count();

//        昨日审核视频数
//        今日审核视频数
            $shenhe_y = VideoEvent::where("check_time", ">=", $yesterdaystart)
                ->where("check_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $shenhe_t = VideoEvent::where("check_time", ">=", date('Y-m-d 00:00:00'))
                ->count();

//        还需审核视频数
            $need_shenhe = VideoEvent::where("status", 3)
                ->where("check", 0)
                ->count();



            $str .= "\n昨日淘宝下载视频数：{$tb_export_y}\n";
            $str .= "今日淘宝下载视频数：{$tb_export_t}\n";
                    
            $str .= "昨日审核视频数：{$shenhe_y}\n";
            $str .= "今日审核视频数：{$shenhe_t}\n";
            $str .= "还需审核视频数：{$need_shenhe}";
        } else {
//            昨日标注的视频数量：
//            今日标注的视频数量：
            $biaozhu_y = VideoProductVideos::where("check", "<>", 0)
                ->where("uid", $uid)
                ->where("get_time", ">=", $yesterdaystart)
                ->where("get_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $biaozhu_t = VideoProductVideos::where("check", "<>", 0)
                ->where("uid", $uid)
                ->where("get_time", ">=", date('Y-m-d 00:00:00'))
                ->count();
//            昨日生产视频数
//            今日生产视频数
            $create_y = VideoEvent::where("uid", $uid)
                ->where("create_time", ">=", $yesterdaystart)
                ->where("create_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $create_t = VideoEvent::where("uid", $uid)
                ->where("create_time", ">=", date('Y-m-d 00:00:00'))
                ->count();
//            昨日审核视频数
//            今日审核视频数
            $shenhe_y = VideoEvent::where("check_uid", $uid)
                ->where("check_time", ">=", $yesterdaystart)
                ->where("check_time", "<", date('Y-m-d 00:00:00'))
                ->count();
            $shenhe_t = VideoEvent::where("check_uid", $uid)
                ->where("check_time", ">=", date('Y-m-d 00:00:00'))
                ->count();
            $str = "昨日标注的视频数量：{$biaozhu_y}\n";
            $str .= "今日标注的视频数量：{$biaozhu_t}\n";

            $str .= "昨日生产视频数：{$create_y}\n";
            $str .= "今日生产视频数：{$create_t}\n";

            $str .= "昨日审核视频数：{$shenhe_y}\n";
            $str .= "今日审核视频数：{$shenhe_t}";
        }
        echo $str;
    }


    public function upDouyinTest(Request $request)
    {
        $params = $request->get();
        $res = [];
        $product = VideoProduct::where("douyin_pid", $params["douyin_pid"])->findOrEmpty();
        if (!$product->isEmpty()) {
            $product->douyin_test = $params["douyin_test"];
            $res = $product->save();
        }
        return writeJson(200, $res, '请求成功');

    }

    public function userData()
    {
        $yesterday = strtotime("-1 day");
        $yesterdaystart = date('Y-m-d 00:00:00', $yesterday);

        $result = [];
        $uids = [];
        $video_download_group = Config::where("name", "video_download_group")->select()->toArray();
        foreach ($video_download_group as $val) {
            $cur_group = json_decode($val["value"], true);
            foreach ($cur_group as $g) {
                $item = [];
                $item["uid"] = $g;
                $item["username"] = "";
                $item["biaozhu_y"] = 0;
                $item["biaozhu_t"] = 0;
                $item["shengchan_y"] = 0;
                $item["shengchan_t"] = 0;
                $item["shenhe_y"] = 0;
                $item["shenhe_t"] = 0;
                $result[] = $item;
                $uids[] = $g;
            }
        }
//            昨日标注的视频数量：
//            今日标注的视频数量：
        $biaozhu_y = VideoProductVideos::field("uid,count(*) c")
            ->where("check", "<>", 0)
            ->where("get_time", ">=", $yesterdaystart)
            ->where("get_time", "<", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($biaozhu_y as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["biaozhu_y"] = $y["c"];
                }
            }
        }
        $biaozhu_t = VideoProductVideos::field("uid,count(*) c")
            ->where("check", "<>", 0)
            ->where("get_time", ">=", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($biaozhu_t as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["biaozhu_t"] = $y["c"];
                }
            }
        }
//            昨日生产视频数
//            今日生产视频数
        $create_y = VideoEvent::field("uid,count(*) c")
            ->where("create_time", ">=", $yesterdaystart)
            ->where("create_time", "<", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($create_y as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["create_y"] = $y["c"];
                }
            }
        }
        $create_t = VideoEvent::field("uid,count(*) c")
            ->where("create_time", ">=", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($create_t as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["create_t"] = $y["c"];
                }
            }
        }
//            昨日审核视频数
//            今日审核视频数
        $shenhe_y = VideoEvent::field("uid,count(*) c")
            ->where("check_time", ">=", $yesterdaystart)
            ->where("check_time", "<", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($shenhe_y as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["shenhe_y"] = $y["c"];
                }
            }
        }
        $shenhe_t = VideoEvent::field("uid,count(*) c")
            ->where("check_time", ">=", date('Y-m-d 00:00:00'))
            ->group("uid")->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($shenhe_t as $y) {
                if ($re["uid"] == $y["uid"]) {
                    $result[$key]["shenhe_t"] = $y["c"];
                }
            }
        }
        $users = LinUser::whereIn("id", $uids)->select()->toArray();
        foreach ($result as $key=>$re) {
            foreach ($users as $y) {
                if ($re["uid"] == $y["id"]) {
                    $result[$key]["username"] = $y["username"];
                }
            }
        }
        return writeJson(200,$result,"成功");

    }

    public function resetProduct()
    {
        $res = VideoProduct::where("status", 3)->update([
            "status"=>1
        ]);
        return writeJson(200,$res,"成功");
    }
}